package com.ktjy.config;

import com.ktjy.filter.JwtTokenFilter;
import com.ktjy.handle.MyAccessDeniedHandler;
import com.ktjy.handle.MyAuthenticationEntryPoint;
import com.ktjy.handle.MyLogoutSuccessHandler;
import com.ktjy.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig {
    @Autowired
    MyAccessDeniedHandler myAccessDeniedHandler;
    @Autowired
    MyLogoutSuccessHandler myLogoutSuccessHandler;
    @Autowired
    MyAuthenticationEntryPoint myAuthenticationEntryPoint;
    @Autowired
    JwtTokenFilter JwtTokenFilter;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        //配置权限
        httpSecurity.authorizeHttpRequests(authz->
            authz
                .requestMatchers("/login").permitAll()///login接口所有人都能访问
//                .requestMatchers("/main").hasAuthority("adminN")
                .anyRequest().authenticated()//其他的接口必须登录才能访问
        );
        //自定义异常处理
        httpSecurity.exceptionHandling(ex->
            ex.accessDeniedHandler(myAccessDeniedHandler)
                .authenticationEntryPoint(myAuthenticationEntryPoint)

        );

        //退出配置
        httpSecurity.logout(out-> out.logoutUrl("/logout")
                .logoutSuccessHandler(myLogoutSuccessHandler));

        //关闭防火墙
        httpSecurity.csrf(csrf->csrf.disable());

        //配置jwt过滤器
        httpSecurity.addFilterBefore(JwtTokenFilter, UsernamePasswordAuthenticationFilter.class);


        return httpSecurity.build();
    }
}
